package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictExcelListener;
import com.atguigu.yygh.common.result.Result;

import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author lijing
 * @since 2025-04-28
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;
    @Override
    public IPage<Dict> selectDictList(Dict dict) {
        Page<Dict> page = this.page(new Page<>(1, 10),
                new LambdaQueryWrapper<Dict>()
                        .eq(Dict::getId, dict.getId()));
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteDict(Long id) {
        if (this.removeById(id)) {
            return Result.ok("删除成功");
        }
        return Result.fail("删除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertDict(Dict dict) {
        if (this.save(dict)) {
            return Result.ok("新建成功");
        }
        return Result.fail("新建失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateDict(Dict dict) {
        if (this.updateById(dict)) {
            return Result.ok("更新成功");
        }
        return Result.fail("更新失败");
    }

    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> queryList(Long id) {
        List<Dict> dicts = baseMapper.selectList(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getParentId, id)).stream().peek(dict -> {
            Integer count = baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, dict.getId()));
            dict.setHasChildren(count > 0);
        }).collect(Collectors.toList());
        return dicts;
    }



    @Override
    public void exportData(HttpServletResponse response) {
        List<DictEeVo> list = dictMapper.queryList();
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("数据导出失败");
        }
    }

    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictExcelListener(dictMapper)).sheet("数据字典").doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getDictName(String value, String dictCode) {
        if (dictCode != null) {
            Dict dict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
            if (dict != null) {
                return dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value).eq(Dict::getParentId, dict.getId())).getName();
            }
        } else {
            return dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value)).getName();
        }
        return null;
    }

    @Override
    public String getDictNameByValue(String value) {
        return dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value)).getName();
    }
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict codeDict = this.getDictByDictCode(dictCode);
        if(null == codeDict) return null;
        return this.findChildData(codeDict.getId());
    }
    @Override
    public List<Dict> findChildData(Long id) {
        return dictMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
    }

    private Dict getDictByDictCode(String dictCode) {
        return dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
    }


}
